'use strict'
//frameRate设置帧率 
//facingMode设置摄像头 user:前置 environment:后置 left:前置左 right:前置右
//resizeMode 画面是否需要裁剪
//volume音量约束
//sampleRate采样率
//sampleSize采样大小 位深
//echoCancellation 回声
//noiseSuppression 降噪
//autoGainControl 自动增音
//latency 延时
//channelCount 单双通道
//deviceID 设备切换
//groupID 同一个物理设备
//MediaStream.addTrack 添加音频轨 MediaStream.removeTrack 删除音频轨
///MediaStream.getVideoTracks 获取视频轨  MediaStream.getAudioTracks 获取音频轨
//MediaStream.onaddtrack 添加轨触发事件 MediaStream.onremovetrack 伤处轨触发 
//MediaStream.onended 轨结束触发
//MediaRecoder 录制 var media = new MediaRecorder(stream,[option])
//参数 mimeType录制类型 video/webm  audio/webm video/webm;codecs=vp8 video/webm;codecs=h264 audio/webm;codecs=opus
//audioBitsPerSecond 音频码率 videoBitsPerSecond 视频码率 bitsPerSecond 整体码率
//常用API MediaRecorder.start(timeslice)开启录制 stop关闭录制 pause暂停录制 resume 恢复录制 isTypeSupported支持文件格式
//常见时间 MediaRecorder.ondataavailable 数据有效触发 onerror发生错误触发 
//数据存储方式 字符串 Blob ArrayBuffer ArrayBufferView
//getDisplayMedia获取桌面 navigator.mediaDevices.getDisplayMedia(constraints) 
//chrome://flags/#enable-experimental-web-platform-features
//

//获取页面组件
var videoplay = document.querySelector("video#player");
var audioplay = document.querySelector("audio#audioplayer"); 
var audioSource = document.querySelector('select#audioSource');
var audioOutput = document.querySelector("select#audioOutput");
var videoSource = document.querySelector("select#videoSource");
var snapshot = document.querySelector("button#snapshot");
var picture = document.querySelector("canvas#picture");
picture.width=320;
picture.height=240;
var divConstraints = document.querySelector('div#constraints');
var recvideo = document.querySelector("video#recplayer");
var btnRecord = document.querySelector("button#record");
var btnPlay = document.querySelector("button#recplay");
var btnDownload = document.querySelector("button#download");
var buffer;
var mediaRecorder;

//获取特效
var filtersSelect = document.querySelector("select#filter");

//获取流
function gotMediaStream(stream){
	videoplay.srcObject=stream;
	//获取VideoTrack
	var videoTrack = stream.getVideoTracks()[0];
	var videoConstraints =  videoTrack.getSettings();	
	divConstraints.textContent = JSON.stringify(videoConstraints,null,2);
	audioplay.srcObject=stream;

	window.stream=stream;
	//拿到流说明可以去访问设备
	return navigator.mediaDevices.enumerateDevices();
}
//异常处理
function handleError(err){
	console.log("getUserMedisa error:",err);
}
//热处理
function start(){
//获取设备信息
function gotDevices(deviceInfos){
	deviceInfos.forEach(function(deviceInfo){
		//设置选项
		var option = document.createElement("option");
		option.text=deviceInfo.label;
		option.value = deviceInfo.deviceId;
		
		//根据种类进行判断
		if(deviceInfo.kind==="audioinput"){
                        audioSource.appendChild(option);
                }else if(deviceInfo.kind==="audiooutput"){
                        audioOutput.appendChild(option);
                }else if(deviceInfo.kind==="videoinput"){  
                        videoSource.appendChild(option);
                }
	})
}
//判断设备是否存在
if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
	console.log("getUserMedis is not supported!!");
	return;
}else{
	var deviceId = videoSource.value;
	//获取权限
	var constraints = {
		video : {
			width:{max:800,mix:300},
			height:{max:400,min:100},
			frameRate:30,
			deviceId : deviceId ? deviceId :undefined
		},
		audio : {
			noiseSuppression: true,
			echoCancellation: true
		}
	}
	
	// var constraints = {
        //        video : true,
        //       audio : true
        //}
       
	//音视频采集
	navigator.mediaDevices.getUserMedia(constraints)
	.then(gotMediaStream)
	.then(gotDevices)
	.catch(handleError);
}
}
//启动调用
start();
//约束改变修改
videoSource.onchange = start;
//特效处理
filtersSelect.onchange = function(){
	videoplay.className = filtersSelect.value;
}
//截取图片
snapshot.onclick = function(){
	picture.className = filtersSelect.value;
	picture.getContext('2d').drawImage(videoplay,
					0,0,
					picture.width,
					picture.height);
}
//数据存储
function handleDataAvailable(e){
	if(e && e.data && e.data.size >0){
		buffer.push(e.data);	
	}
}
//开始录制
function startRecord(){

	buffer=[];
	
	var options = {
		mimeType:"video/webm;codecs=vp8"
	}
	if(!MediaRecorder.isTypeSupported(options.mimeType)){
	 	console.error(`${options.mimeType} is not supported!`);
		return;
	}
	
	try{
	mediaRecorder = new MediaRecorder(window.stream,options);
	}catch(e){
		console.error("Failed to create MediaRecorder:",e);
		return;
	}
	mediaRecorder.ondataavailable = handleDataAvailable;
	mediaRecorder.start(10);
	
}
//停止录制
function stopRecord(){
	mediaRecorder.stop();
}
//录制
btnRecord.onclick = ()=>{
	if(btnRecord.textContent==="Start Record"){
		startRecord();
		btnRecord.textContent = "Stop Record";
		btnPlay.disabled = true;
		btnDownload.disabled = true;		
	}else{
		stopRecord();
		btnRecord.textContent = "Start Record";
                btnPlay.disabled = false;
                btnDownload.disabled = false;	
	}
}
//播放
btnPlay.onclick = () =>{
	var blob = new Blob(buffer,{type:"video/webm"});
	recvideo.src=window.URL.createObjectURL(blob);
	recvideo.srcObject = null;
	recvideo.controls = true;
	recvideo.play();	
}
//下载
btnDownload.onclick =() =>{
	var blob = new Blob(buffer,{type:'video/webm'});
	var url = window.URL.createObjectURL(blob);
	var a = document.createElement('a');
	a.href = url;
	a.style.display = 'none';
	a.download = "yhz.webm";
	a.click();
}
